package com.wander.concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class CountDownLatchExample {
    public static void main(String[] args) throws InterruptedException {

        int numThreads = 3;
        CountDownLatch countDownLatch = new CountDownLatch(numThreads);

        for (int i = 0; i < numThreads; i++) {
            new Thread(()->{
                System.out.println("子线程： " + Thread.currentThread().getName() + "开始执行！");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("子线程：" + Thread.currentThread().getName() + "完成任务！");
                countDownLatch.countDown();
            }).start();
        }

        System.out.println("主线程等待所有子线程完成任务");
        countDownLatch.await();
        System.out.println("所有子任务已完成任务，主线程继续执行！");
    }
}
